﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//
using Microsoft.Expression.Encoder;
using Microsoft.Expression.Encoder.Profiles;
using Microsoft.Expression.Encoder.Templates;
//
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
/*
Copyright 2010 Mirosław M. Mączka

This file is part of Flac2Wma.

    Flac2Wma is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Foobar is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Foobar; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/
namespace Flac2Wma
{
    class Handler_Wma:IOutputHandler
    {
        public string _AAC_Encoder { get; set; }
        public string _AAC_CommandLine { get; set; }
        //
        public bool DeleteInputFile { get; set; }
        //
        public string InputFileName { get; set; }
        public string OutputFileName { get; set; }
        public string OutputFileNameExtension { get { return ".wma"; } }
        public string OutputFileType { get { return "WMA"; } }
        //
        public string Author { get; set; }
        public string Copyright { get; set; }
        public string Description { get; set; }
        public string Rating { get; set; }
        public string Title { get; set; }
        //
        public string AlbumTitle { get; set; }
        public string Genre { get; set; }
        public int TrackNumber { get; set; }
        public int Year { get; set; }
        public string Composer { get; set; }
        public object MCDI { get; set; }
        //
        public string ErrorMessage { get; set; }
        public string DefaultDownloadPage { get { return "http://www.microsoft.com/expression/products/Encoder4_Overview.aspx"; } }
        //
        private MediaItem mediaItem;
        //
        //
        public int PlayTime { get; set; }
        //
        public Handler_Wma()
        {
            ClearProps();
            //
        }
        //
        public void ClearProps()
        {
            Author = string.Empty;
            Copyright = string.Empty;
            Description = string.Empty;
            Rating = string.Empty;
            Title = string.Empty;
            //
            AlbumTitle = string.Empty;
            Genre = string.Empty;
            TrackNumber = -1;
            Year = -1;
            Composer = string.Empty;
            MCDI = null;
        }
        //
        public bool Do(string wavPathName, string outputDirectory)
        {
            //
            bool retVal = true;
            //
            //ArrayList al = new ArrayList();
            //
            ErrorMessage = "";
            //
            PlayTime = -1;
            //
            InputFileName = wavPathName;
            if (null != outputDirectory)
            {
                OutputFileName = Path.Combine(outputDirectory, Path.GetFileNameWithoutExtension(wavPathName) + OutputFileNameExtension);
            }
            else
            {
                OutputFileName = Path.Combine(Path.GetDirectoryName(wavPathName), Path.GetFileNameWithoutExtension(wavPathName) + OutputFileNameExtension);
            }
            //InputFileName = @"c:\Home\Visual Studio 2008\Projects\WME_Test\pet4.wav";
            //OutputFileName = @"c:\Home\Visual Studio 2008\Projects\WME_Test\pet4.wma";
            //
            try
            {
                //
                mediaItem = new MediaItem(Path.GetFullPath(InputFileName));
                //
                mediaItem.OutputFormat = new WindowsMediaOutputFormat();
                //
                mediaItem.OutputFormat.AudioProfile = new WmaAudioProfile();
                //
                mediaItem.OutputFormat.AudioProfile.Codec = AudioCodec.WmaLossless;
                mediaItem.OutputFormat.AudioProfile.Bitrate = new VariableQualityBitrate(100);
                mediaItem.OutputFormat.AudioProfile.BitsPerSample = 16;
                mediaItem.OutputFormat.AudioProfile.Channels = 2;
                mediaItem.OutputFormat.AudioProfile.SamplesPerSecond = 44100;
                //
                mediaItem.OutputFileName = Path.GetFileName(OutputFileName);
                //
                if ("" != Author)
                {
                    mediaItem.Metadata[MetadataNames.Author] = Author;
                }
                if ("" != Copyright)
                {
                    mediaItem.Metadata[MetadataNames.Copyright] = Copyright;
                }
                if ("" != Description)
                {
                    mediaItem.Metadata[MetadataNames.Description] = Description;
                }
                if ("" != Rating)
                {
                    mediaItem.Metadata[MetadataNames.Rating] = Rating;
                }
                if ("" != Title)
                {
                    mediaItem.Metadata[MetadataNames.Title] = Title;
                }
                //
                if ("" != AlbumTitle)
                {
                    mediaItem.Metadata[MetadataNames.AlbumTitle] = AlbumTitle;
                }
                if ("" != Genre)
                {
                    mediaItem.Metadata[MetadataNames.Genre] = Genre;
                }
                if (TrackNumber >= 0)
                {
                    mediaItem.Metadata[MetadataNames.TrackNumber] = TrackNumber.ToString();//number
                }
                if (Year > 0)
                {
                    mediaItem.Metadata[MetadataNames.Year] = Year.ToString();
                }
                if ("" != Composer)
                {
                    mediaItem.Metadata[MetadataNames.Composer] = Composer;
                }


                //
                //
                Job job = new Job();
                job.MediaItems.Add(mediaItem);
                
                
                job.CreateSubfolder = false;
                job.OutputDirectory = Path.GetDirectoryName(Path.GetFullPath(OutputFileName));

                // encodes job
                job.Encode();
                job.Dispose();
                //
                //
                //
            }
            catch (Exception e)
            {
                ErrorMessage = e.Message;
                System.Threading.Thread.Sleep(5000);
                retVal = false;
            }
            finally
            {
                // (enc != null) Marshal.ReleaseComObject(enc);
                //if (audience != null) Marshal.ReleaseComObject(audience);
                //
                if (DeleteInputFile)
                {
                    File.Delete(wavPathName);
                }
                //
            }
            //
            return retVal;
        }

        //
        //
        public bool IsEncoderOK()
        {
            if(!InstalledApp.isInstalled())
            {
                //
                //string url = "http://www.microsoft.com/expression/products/Encoder4_Overview.aspx";
                //
                //System.Windows.Forms.MessageBox.Show("Brak Expression Encoder 4\nzainstaluj!", "Expression Encoder 4");
                //
                //System.Diagnostics.Process p = new System.Diagnostics.Process();
                //p.StartInfo.UseShellExecute = true;
                //p.StartInfo.FileName = url;
                //p.Start();
                //
                return false;
            }
            return true;
        }
        //
        //
        // różnica o 1 w PlayTime najwyraźniej się zdarza
        // empiria - różnice o 1 są całkiem częste, teraz mam różnicę o 2
        private const int MaxDiferenceInTicks = 10;
        public bool IsOtputFileOK(int playTime)
        {
            //
            if (File.Exists(OutputFileName))
            {
                FileInfo fi = new FileInfo(OutputFileName);
                //
                if (0 == fi.Length) return false;
                //
                int nTicks = -1;
                if (Form1.mi.getPlayTimeForFile(OutputFileName, out nTicks))
                {
                    PlayTime = nTicks;
                }
                //
                //
                if ((-1 == playTime) || (-1 == PlayTime) || Math.Abs(playTime - PlayTime) > MaxDiferenceInTicks) return false;
                //
                //if (wmaFileLength > flacFileLength) return false;
                //
                /*
                long diff = Math.Abs(wmaFileLength - flacFileLength);
                if ((Math.Max(wmaFileLength, flacFileLength) / 5) < diff)// 20%
                {
                    return false;
                }
                */
                return true;
            }
            return false;
        }
        //
    }//class
}//namespace
